<?php

namespace app\admin\controller\user;

use app\common\controller\Backend;
use app\common\library\Client;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 用户管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{

    protected $searchFields = 'id,username,mobile';
    protected $noNeedLogin = ['resetUserGroup'];
    protected $noNeedRight = ['resetUserGroup'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $result = Client::instance()->userList($this->request->request());

            if ($result['rows']) {
                $user_ids = array_column($result['rows'], 'id');

                $users = \app\common\model\User::alias('user')
                    ->join('__USER_GROUP__ group', 'user.group_id = group.id')
                    ->whereIn('user.id', $user_ids)
                    ->column('user.id,user.group_end_time,group.name group_name', 'user.id');

                foreach ($result['rows'] as $key => $row) {
                    if (isset($users[$row['id']])) {
                        $result['rows'][$key]['group_name'] = $users[$row['id']]['group_name'];
                        $result['rows'][$key]['group_end_time'] = $users[$row['id']]['group_end_time'];
                    }
                }
            }

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {

    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = Client::instance()->userProfile($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $user = \app\common\model\User::where('id', $row['id'])->field('id,group_id,group_end_time')->find();
        if ($user) {
            $row['group_id'] = $user['group_id'];
            $row['group_end_time'] = $user['group_end_time'];
        } else {
            $row['group_id'] = 0;
            $row['group_end_time'] = 0;
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {

            $group_id = $this->request->post('group_id');
            $group_type = $this->request->post('group_type', 1);
            $group_end_time = $this->request->post('group_end_time');

            if ($group_id && $group_type == 2 && !$group_end_time) {
                $this->error('请选择到期时间');
            }

            if ($user) {
                if ($group_id) {
                    $user->group_id = $group_id;
                    if ($group_type == 2) {
                        $user->group_end_time = strtotime($group_end_time);
                    } else {
                        $user->group_end_time = 0;
                    }
                } else {
                    $user->group_id = $group_id;
                    $user->group_end_time = null;
                }
                $user->save();
            } else {
                $user = new \app\common\model\User();
                $user->id = $row['id'];
                if ($group_id) {
                    $user->group_id = $group_id;
                    if ($group_type == 2) {
                        $user->group_end_time = strtotime($group_end_time);
                    } else {
                        $user->group_end_time = 0;
                    }
                }else {
                    $user->group_id = $group_id;
                    $user->group_end_time = null;
                }
                $user->save();
            }

            $this->success();
        }

        $user_group = \app\admin\model\UserGroup::whereIn('school_id', $this->auth->getSchoolIds())->column('id,name');
        $group[0] = '请选择';
        foreach ($user_group as $key => $value) {
            $group[$key] = $value;
        }
        $row['group_type'] = 0;
        $row['group_end_time'] = '';
        if ($row['group_end_time'] == 0) {
            $row['group_type'] = 1;
        } else if ($row['group_end_time'] > 0) {
            $row['group_type'] = 2;
            $row['group_end_time'] = date('Y-m-d H:i:s', $row['group_end_time']);
        }
        $group_type = ['0' => '请选择', '1' => '长期', '2' => '短期'];
        $this->view->assign('groupTypeList', build_select('group_type', $group_type, $row['group_type'], ['class' => 'form-control selectpicker group_type']));
        $this->view->assign('groupList', build_select('group_id', $group, $row['group_id'], ['class' => 'form-control selectpicker']));

        $this->view->assign("row", $row);
        return $this->view->fetch();

    }

    public function del($ids = '')
    {
        
    }

    /**
     * @User ZhenZiHan
     * @Date 2020/1/6
     *
     */
    public function resetUserGroup()
    {
        \app\admin\model\User::where('group_end_time', '<=', time())->where('group_end_time', '>', 0)->update(['group_id' => 0, 'group_end_time' => null]);
    }

}
